package edu.bit.water.service;


import edu.bit.water.dao.RolesDao;
import edu.bit.water.entity.Roles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Roles数据表对应的service类
 * @Author: PH
 */
@Service
public class RolesService {

    @Autowired
    private RolesDao RolesDao;

    public List<Roles> selectRoles() {
        return RolesDao.selectRoles();
    }

    public List<Roles> selectRolesByComId(String companyId) {return RolesDao.selectRolesByComId(companyId);}

    public Map<String, Object> insertRoles(Roles Roles) {
        Map<String, Object> result = new HashMap<>();
        Integer id = RolesDao.getMaxId();
        if (id != null) {
            Roles.setId(id + 1);
        }
        int tmp = RolesDao.insertRoles(Roles);
        if (tmp == 1) {
            result.put("status", "success");
        }
        else {
            result.put("status", "failed");
        }
        return result;
    }

    public Map<String, Object> deleteRoles(List<String> ids) {
        Map<String, Object> result = new HashMap<>();
        int flag= 1;
        String allRoleName="";
        for (int i = 0; i < ids.size(); i++) {
            int tmp = 0;//该角色删除是否成功
            int roleid =Integer.parseInt(ids.get(i));
            int cnt = RolesDao.deleteValidate(roleid);//使用该角色的用户数量
            String roleName = RolesDao.selectRoleNameByRoleId(roleid);
            if(cnt>=1){
                allRoleName = allRoleName+roleName+" ";
                result.put("msg",allRoleName+"角色有用户使用");
                flag=2;
            }
            else{
                tmp = RolesDao.deleteRoles(roleid);
                if (tmp != 1) {
                    flag = 0;
                    result.put(roleName,"删除失败");
                }
            }
        }
        if(flag==1){
            result.put("status", "success");
        }
        else if(flag==0){
            result.put("status", "failed");
        }
        else{
            result.put("status", "used");
        }
        return result;
    }


    public int deleteUserRoleRel(int userid){
        int result = RolesDao.deleteUserRoleRel(userid);
        return result;
    }



    public Map<String, Object> updateRoles(Roles Roles) {
        Map<String, Object> result = new HashMap<>();
        int tmp = RolesDao.updateRoles(Roles);
        if(tmp == 1) {
            result.put("status", "success");
        }
        else {
            result.put("status", "failed");
        }
        return result;
    }
}